package com.jbm.jbmsupplier.util;

import java.io.File;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Sun on 2016/11/22.
 */

public class SysLog
{
	public static int SYS_LOG_LEVEL_BREAK = 0x00000001;
	public static int SYS_LOG_LEVEL_ERROR = 0x00000002;
	public static int SYS_LOG_LEVEL_WARNNING = 0x00000004;
	public static int SYS_LOG_LEVEL_RUNSTATUS = 0x00000008;
	public static int SYS_LOG_LEVEL_DEBUG = 0x00000010;

	public static SysLog g_syslog = null;

	private int m_filelevel;
	private int m_screenlevel;
	private long m_serial;
	private String m_filename;

	public SysLog()
	{
		m_filelevel = 0;
		m_screenlevel = 0;
		m_serial = 0l;
	}

	public SysLog ( String filename, int filelevel, int screenlevel )
	{
		this();

		m_filename = filename;
		m_filelevel = filelevel;
		m_screenlevel = screenlevel;
	}

	public void MakeLog ( int loglevel, String slog, Object... args )
	{
		if ( ( loglevel & m_filelevel ) == 0 && ( loglevel & m_screenlevel ) == 0 )
			return;

		String log = String.format(slog,args);

		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

		synchronized (this)
		{
			String logtext;
			if ( m_serial == 0 )
				logtext = String.format(
						"\r\n\r\n\r\nLT[%s]LL[%04x]SN[%05d]  %s\r\n",df.format(new Date()),loglevel,m_serial++,log
				);
			else
				logtext = String.format(
						"LT[%s]LL[%04x]SN[%05d]  %s\r\n",df.format(new Date()),loglevel,m_serial++,log
				);

			if ( ( loglevel & m_filelevel ) > 0 )
			{
				try
				{
					String logfolder = "e:/jbm/log";
					File path = new File ( logfolder );

					if ( !path.exists())
						path.mkdirs();
					RandomAccessFile logf = new RandomAccessFile(logfolder+"/"+m_filename, "rw");
					logf.seek(logf.length());
					logf.write(logtext.getBytes());
					logf.close();
				}catch (Exception e)
				{
					String me = e.getMessage();
				};
			}

			if ( ( loglevel & m_screenlevel ) > 0 )
				System.out.println(logtext);
		}
	}
}
